package com.clothes.aweiDoExercises.utils;

import cn.hutool.core.collection.CollUtil;
import com.clothes.aweiDoExercises.common.ErrorCode;
import com.clothes.aweiDoExercises.config.AiConfig;
import com.clothes.aweiDoExercises.exception.BusinessException;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionChoice;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 通用的AI调用类
 */
@Component
public class AiUtils {
    @Resource
    private AiConfig aiConfig;

    @Lazy
    @Resource
    private ArkService  aiService;

    private final String DEFAULT_MODEL = "deepseek-v3-250324"; // 默认模型名称

    /**
     * ai 请求客户端
     * @return
     */
    @Bean // 注册为 Spring Bean
    public ArkService aiService() {
        // 从环境变量中获取您的 API Key。此为默认方式，您可根据需要进行修改
        String apiKey = aiConfig.getApiKey();
        // 此为默认路径，您可根据业务所在地域进行配置
        String baseUrl = aiConfig.getBaseUrl();
        ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        ArkService service = ArkService.builder()
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .baseUrl(baseUrl)
                .apiKey(apiKey).build();
        return  service;
    }


    /**
     * 调取ai接口,返回响应结果
     * @return
     */
    public String doChat(List<ChatMessage> messages,String model){

        //构造请求
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 指定您创建的方舟推理接入点 ID，此处已帮您修改为您的推理接入点 ID
                //.model("deepseek-v3-250324 ")
                .model(model) //大模型的名称
                .messages(messages)
                .build();
        //调用接口发送请求
        List<ChatCompletionChoice> choices = aiService.createChatCompletion(chatCompletionRequest).getChoices();

        //获取响应的第一条信息
        if (CollUtil.isNotEmpty(choices)){
            return (String) choices.get(0).getMessage().getContent();
        }

        throw new BusinessException(ErrorCode.OPERATION_ERROR,"AI 接口调用失败,没有返回结果");

        //aiService.shutdownExecutor();  //关闭线程池,这个前期防止中断出现一些问题暂时先不关

    }

    /**
     * 调取ai接口,返回响应结果（允许传入消息列表使用默认模型）
     * @return
     */
    public String doChat(List<ChatMessage> messages){
        return doChat(messages,DEFAULT_MODEL);
    }



    /**
     * 调取ai接口,返回响应结果,这个是重载方法用户只需填写用户预设
     * @param userPrompt
     * @return
     */
    public String doChat(String userPrompt){
        return doChat("",userPrompt,DEFAULT_MODEL);
    }

    /**
     * 调取ai接口,返回响应结果,这个是重载方法用户只需填系统预设和用户预设
     * @param userPrompt
     * @return
     */
    public String doChat(String systemPrompt,String userPrompt){
        return doChat(systemPrompt,userPrompt,DEFAULT_MODEL);
    }

    /**
     * 调取ai接口,返回响应结果
     * @return
     */
    public String doChat(String systemPrompt,String userPrompt,String model){

        //构造消息列表
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(userPrompt).build();
        messages.add(systemMessage);
        messages.add(userMessage);

        return doChat(messages,model);

        //aiService.shutdownExecutor();  //关闭线程池,这个前期防止中断出现一些问题暂时先不关

    }


}
